import { createSlice } from '@reduxjs/toolkit'

const cartSlice = createSlice({
    name: 'cart',
    initialState: {
        cartList: []
    },
    reducers: {
        addCart(state, { payload }) {
            // 判断当前商品在 cartList中是否存在，如果存购买数量 + 1
            let index = state.cartList.findIndex(item => {
                return item.id === payload.id
            })
            if (index === -1) {
                // 不存在新增
                console.log('cart payload: ', payload)
                state.cartList.push({
                    ...payload,
                    buyNum: 1 // 购买数量1
                })
            } else {// 存在
                state.cartList[index].buyNum += 1
            }

        },
        //
        addNum(state, { payload }) {
            console.log('payload: ', payload)
            state.cartList = state.cartList.map(item => {
                if (item.id === payload) {
                    item.buyNum += 1;
                }
                return item;
            })
        },
        decNum(state, { payload }) {
            // 当前要修改buyNum元素的索引值
            let index = state.cartList.findIndex(item => item.id === payload);
            let count = state.cartList[index].buyNum - 1
            if(count <= 0){// 删掉
                state.cartList.splice(index,1)
            }else{// 数量 - 1
                state.cartList[index].buyNum = count;
            }
            
        }
    }
})

export const { addCart, addNum, decNum } = cartSlice.actions;
export default cartSlice.reducer;